﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ShortUrl.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ToShort()
        { 
            string refer = ESP.Tool.ESPRequest.GetUrl(); //ESP.Tool.ESPRequest.GetUrlReferrer();
            string errUrl = ESP.Tool.SystemDefinition.SystemSetting.GetAppSettingValue("ErrUrl");
            int maxLength = int.Parse(ESP.Tool.SystemDefinition.SystemSetting.GetAppSettingValue("maxLengthUrl"));
            if (refer.Length > maxLength)
            {
                return Redirect(errUrl);
            }
            string[] urlArr = refer.Split('/');

            string key = urlArr[urlArr.Length - 1];
            string SourceUrl = Models.ShortUrlModel.GetSourceUrl(key);
            if (string.IsNullOrEmpty(SourceUrl) || SourceUrl.Length> (maxLength*5))
            {
                string[] newUrl = errUrl.Split(',');
                Random rnd = new Random();
                int index = rnd.Next(newUrl.Length);

                SourceUrl = newUrl[index];
            } 

            return Redirect(SourceUrl); 
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }




    }
}